import { createWebHistory, createRouter } from "vue-router";
import routes from "./router-pages";
import { useTokenStore } from "@/store/user";
import { useRoutesStore } from "@/store/router";
import { ElMessage } from "element-plus";

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 前置路由守卫
router.beforeEach((to, from, next) => {
  const isLogin = useTokenStore().token && localStorage.getItem("tokenStore");
  console.log(from);
  document.title = (to.meta.title as string) || "默认标题";

  // 检查是否需要登录
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!isLogin) {
      ElMessage.warning("您尚未登录，请先登录！");
      next("/login-register");
    } else {
      next();
    }
  } else {
    // 如果用户已经登录并且尝试访问登录注册页面，重定向到主页
    if (to.path === "/login-register" && isLogin) {
      next("/index");
      ElMessage.warning("您已登录，无需再次登录！");
    } else {
      next();
    }
  }

  // 记录路由
  useRoutesStore().addRoute(to);
});

// 后置路由守卫
router.afterEach((to, from) => {
  console.log("afterEach", to, from);
});

export default router;
